package cn.wolfcode.thread;

import java.util.concurrent.*;

/**
 * 1.常规线程池
 * 2.线程池--拒绝策略RejectedExecutionHandler --扩展
 */
public class TestThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1创建线程池
//        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2线程池--拒绝策略RejectedExecutionHandler --扩展
        ExecutorService pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1), new RejectedExecutionHandler() {
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.out.println("overFlow");
            }
        });



        //2将线程交给线程池管理
        for (int i = 0; i < 5; i++) {
        PoolDemo runnableDemo = new PoolDemo("task"+i);
            pool.submit(runnableDemo);
        }
        /*for (int i = 0; i <10 ; i++) {
            Future<Integer> res = pool.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    int sum = 0;
                    for (int i = 0; i < 5; i++) {
                        sum += i;
                    }
                    return sum;
                }
            });
            System.out.println(res.get());
        }*/
        //3关闭
        pool.shutdown();
    }
}

class PoolDemo implements Runnable {
    private String name;
    public PoolDemo(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i+"name"+name);
        }
    }
}